package com.yeskery.nut.http.bio;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.http.BaseResponse;
import com.yeskery.nut.util.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * 基于 <b>BIO</b> 模式下的 {@link com.yeskery.nut.core.Response} 的实现，该类继承自 {@link BaseResponse}
 * @author sprout
 * @version 1.0
 * 2019-03-19 00:32
 *
 * @see com.yeskery.nut.core.Response
 * @see com.yeskery.nut.http.BaseResponse
 */
public class BioResponse extends BaseResponse {

	/** 用于输出数据的输出流对象 */
    private final transient OutputStream outputStream;

	/**
	 * 构建一个 {@link BioResponse} 对象
     * @param nutApplication Nut应用对象
	 * @param outputStream 输出流对象
	 */
	public BioResponse(NutApplication nutApplication, OutputStream outputStream) {
        super(nutApplication);
        this.outputStream = outputStream;
    }

    @Override
    protected void writeHeaderBytes(byte[] headers) {
        IOUtils.writeByteArray(outputStream, headers);
    }

    @Override
    protected void writeBodyBytes(byte[] bytes) {
        IOUtils.writeByteArray(outputStream, bytes);
    }

    @Override
    protected void writeBodyInputStream(InputStream inputStream) {
        IOUtils.transferInputStream(inputStream, outputStream);
    }

    @Override
    protected void writeBytes(byte[] headers, byte[] bytes) {
        byte[] data = new byte[bytes.length + headers.length];
        System.arraycopy(headers, 0, data, 0, headers.length);
        System.arraycopy(bytes, 0, data, headers.length, bytes.length);
        IOUtils.writeByteArray(outputStream, data);
        output = true;
    }

    @Override
    protected void writeInputStream(byte[] headers, InputStream inputStream) {
        IOUtils.writeByteArray(outputStream, headers);
        IOUtils.transferInputStream(inputStream, outputStream);
        output = true;
    }
}
